<template>
  <!-- 地图展示 -->
  <div id="map" ref="mapPart">
    <!-- <p id="currentPoint">
      <i class="el-icon-location"></i>
      {{ currentPoint.lat?currentPoint.lat.toFixed(4):"-" }}, {{ currentPoint.lng?currentPoint.lng.toFixed(4):"-" }}
    </p> -->
    <!-- <dl class="tipItem">
      <dt>图例</dt>
      <dd style="border-bottom:1px solid #afa9a9;">
        <img src="~@/assets/images/marker.png" />
        <span>机场</span>
      </dd>
      <dd>
        <img src="~@/assets/images/airpoint.png" />
        <span>航路点</span>
      </dd>
    </dl> -->
  </div>
</template>

<script>
  import { Loading } from 'element-ui';
  import { mapGetters } from 'vuex'
  import * as turf from '@turf/turf';

  var loadingInstance;
  var airspaceLayer = null; // 空域图层
  var airportLayer = null;  // 机场图层
  var pointLayer = null;  // 航路点层
  var lineLayer = null, linePointLayer = null; // 航线图层|航线点位图层
  // var sector;
  // var myIcon = L.icon({
  //   iconUrl: require('@/assets/images/station.png'),
  //   iconSize: [18, 22],
  //   iconAnchor: [22, 94],
  //   popupAnchor: [-3, -76],
  //   shadowUrl: 'my-icon-shadow.png',
  //   shadowSize: [68, 95],
  //   shadowAnchor: [22, 94]
  // });
  var fairwayLayer;
  var drawnItems;
  export default {
    name: 'MapShow',
    data() {
      return {
        map:null,
        airspaceList:[],  // 空域列表
        airspaceLayerGroup:[],  // 空域图层
        
        airportList:[],   // 机场列表
        airportLayerGroup:[],  // 机场图层

        airpointList:[],   // 航路点列表
        airpointLayerGroup:[],  // 航路点图层

        airlineList:[],   // 航线列表
        airlineLayerGroup:[],  // 航线图层
        checkItem:["airspace","airport","airpoint","airline"], // 选中的要显示的信息
        currentPoint:{
          lng:null,
          lat:null
        },
      }
    },
    mounted(){
      this.$nextTick(()=>{
        console.log("mounted......")
        // 清除地图容器
        // let container = L.DomUtil.get("map");
        // let container = L.DomUtil.get(this.$refs.mapPart);
        // if(container) container._leaflet_id = null;

        if(this.roles.includes('R1') || this.roles.includes('admin')) this.initMap();
      })
    },
    computed:{
      ...mapGetters([ 'roles' ])
    },
    methods:{
      // 初始化地图
      initMap(){
        if(this.map){
          let container = L.DomUtil.get(this.$refs.mapPart);
          if(container) container._leaflet_id = null;
        }
        console.log("map", this.map)

        // var normalm = L.esri.tiledMapLayer({
        //   url: 'https://map.geoq.cn/ArcGIS/rest/services/ChinaOnlineStreetWarm/MapServer'
        // });
        // var satelliteImgm = L.tileLayer.chinaProvider('TianDiTu.Satellite.Map');
        // var satelliteImga = L.tileLayer.chinaProvider('TianDiTu.Satellite.Annotion');

        var normalm = L.tileLayer.chinaProvider('GaoDe.Normal.Map', {
          maxZoom: 18,
          minZoom: 4
        });
        var satelliteImgm = L.tileLayer.chinaProvider('GaoDe.Satellite.Map');
        var satelliteImga = L.tileLayer.chinaProvider('GaoDe.Satellite.Annotion');
        var satellite = L.layerGroup([satelliteImgm, satelliteImga]);
        var normal = L.layerGroup([normalm]);
        let layerName = {
          "卫星地图":satellite,
          "普通地图":normalm
        }
        // this.map = L.map("map",{
        this.map = L.map(this.$refs.mapPart,{
          center:[40.2646, 116.3991],
          zoom:8,
          // layers:[satellite, normal],
          preferCanvas:true,
          zoomControl:false,
          attributionControl:false,
          inertia:false,
          trackResize:true
        });
        L.control.layers(layerName).addTo(this.map);
        normalm.addTo(this.map);
        // 比例尺
        L.control.scale({imperial:false}).addTo(this.map);
        // 缩放
        L.control.zoom().addTo(this.map);
        // this.map.setView([data.latGCJ02, data.lonGCJ02], 8)
        
        // 绘制扇形
        // this.drawSector([31.59586, 120.2995], 0.02, -60, 45, 800);

        // 监听地图点击事件
        this.map.on('click', (e)=>{
          // console.log(e)
        })

        // 监听地图鼠标移动事件
        this.map.on('mousemove', (e)=>{
          // this.currentPoint.lng = e.latlng.lng;
          // this.currentPoint.lat = e.latlng.lat;
        })

        // 监听地图移动事件
        // this.map.on('move', (e)=>{})

        // 监听地图缩放事件
        this.map.on('zoom', (e)=>{
          // if(e.target._zoom <= 7 && this.isShow){
          //   this.isShow = false;
          //   document.getElementsByClassName("iconLabel").forEach(item=>{
          //     item.style.display = "none";
          //   })
          // }
          // if(e.target._zoom > 7 && !this.isShow){
          //   this.isShow = true;
          //   document.getElementsByClassName("iconLabel").forEach(item=>{
          //     item.style.display = "block";
          //   })
          // }
        })

        window.onresize = ()=>{
          this.map.invalidateSize(true);
          // this.map.fitBounds([
          //   [31.59102002701019, 120.30037886225469],
          //   [31.589045999457486, 120.30016433385363],
          //   [31.589064277682226, 120.30222380650356],
          //   [31.59586, 120.2995]
          // ]);
        }
      },

      // 绘制空域
      drawAirspace(airspaceList, color){
        console.log("----map", this.map)
        console.log(airspaceList, color);
        this.airspaceList = airspaceList;
        if(airspaceLayer) this.map.removeLayer(airspaceLayer);
        this.airspaceLayerGroup = [];
        if(airspaceList.length){
          let arr = [];
          airspaceList.map((item, i)=>{
            if(item.spacePoints && item.spacePoints.length){
              switch (item.spaceShape) {
                case 1:
                  // 多边形
                  item.spacePoints.map((vo, index)=>{
                    arr.push([vo.pLat, vo.pLng]);
                    if(index == item.spacePoints.length-1){
                      this.airspaceLayerGroup.push(L.polygon(arr, {color:color}).bindPopup(item.spaceName));
                    }
                  })
                  break;
                case 2:
                  // 圆形
                  let radius = Number(item.spacePoints[0].pRadius) * 1000;
                  this.airspaceLayerGroup.push(L.circle([item.spacePoints[0].pLat, item.spacePoints[0].pLng], {
                    color: color,
                    // fillColor:'transparent',
                    radius: radius
                  }).bindPopup("<div style='padding:5px;'><b>"+item.spaceName+"(半径:"+item.spacePoints[0].pRadius+"km)</b><br/>"+(item.spacePoints[0].pLat<0?'S ':'N ')+this.D2Dms(item.spacePoints[0].pLat)+","+(item.spacePoints[0].pLng<0?'W ':'E ')+this.D2Dms(item.spacePoints[0].pLng)+"</div>"));
                  break;
                case 3:
                  // 扇形
                  var points = this.getPoints([item.spacePoints[0].pLat, item.spacePoints[0].pLng], item.spacePoints[0].pRadius, item.spacePoints[0].pAngleStart, item.spacePoints[0].pAngleEnd, 800);
                  points[points.length] = points[0];
                  this.airspaceLayerGroup.push(L.polygon(points, {color:color}).bindPopup(item.spaceName))
                  break;
              }
            }
            if(i == airspaceList.length-1){
              airspaceLayer = L.layerGroup(this.airspaceLayerGroup.reverse());
              airspaceLayer.addTo(this.map);
              this.map.setView([item.spacePoints[0].pLat, item.spacePoints[0].pLng], 8);
            }
          })
        }
      },

      // 绘制机场
      drawAirport(airportList){
        console.log(airportList);
        this.airportList = airportList;
        if(airportLayer) this.map.removeLayer(airportLayer);
        this.airportLayerGroup = [];
        if(!airportList.length) return false;
        airportList.map((info, i)=>{
          if(info.portLongValue && info.portLatValue){
            var airportImg = "";
            switch (info.portType) {
              case 1:
                // 机场
                airportImg = require("@/assets/images/airport.png");
                break;
              case 2:
                // 野外起降点
                airportImg = require("@/assets/images/airportField.png");
                break;
              case 3:
                // 临时起降点
                airportImg = require("@/assets/images/airportTmp.png");
                break;
            
              default:
                break;
            }
            var pointIcon = L.divIcon({
              html:'<img class="my-div-image" style="width:20px;height:20px;" src="'+airportImg
              +'" /><span class="iconLabel" style="margin:-5px 0 0 -8px;color:#595656;background-color:transparent;white-space:nowrap;">'
              +info.portName+'</span>',
              className: 'my-div-icon'
            });
            // let pointIcon = L.icon({
            //   iconUrl: require('@/assets/images/marker.png'),
            //   iconSize: [10, 10]
            // });
            let marker = L.marker([info.portLatValue, info.portLongValue], {icon: pointIcon})
            .bindPopup("<div style='padding:5px;'><b>"+info.portName+"</b><br/>"+info.portLatitude+","+info.portLongitude+"</div>");
            this.airportLayerGroup.push(marker);
          }
          if(i == airportList.length-1){
            airportLayer = L.layerGroup(this.airportLayerGroup.reverse());
            airportLayer.addTo(this.map);
            this.map.setView([info.portLatValue, info.portLongValue], 8);
          }
        })
      },

      // 绘制航路点
      drawAirpoint(airpointList){
        console.log(airpointList);
        this.airpointList = airpointList;
        if(pointLayer) this.map.removeLayer(pointLayer);
        this.airpointLayerGroup = [];
        if(!airpointList.length) return false;
        airpointList.map((info, i)=>{
          if(info.pointLngValue && info.pointLatValue){
            let pointIcon = L.icon({
              iconUrl: require('@/assets/images/airpoint.png'),
              iconSize: [18, 22]
            });
            let marker = L.marker([info.pointLatValue, info.pointLngValue], {icon: pointIcon})
            .bindPopup("<div style='padding:5px;'><b>"+info.pointName+"</b><br/>"+info.pointLatitude+","+info.pointLongitude+"</div>");
            this.airpointLayerGroup.push(marker);
          }
          if(i == airpointList.length-1){
            pointLayer = L.layerGroup(this.airpointLayerGroup.reverse());
            pointLayer.addTo(this.map);
            this.map.setView([info.pointLatValue, info.pointLngValue], 8);
          }
        })
      },

      // 绘制航线
      drawAirline(lineList, color){
        console.log(lineList, color);
        if(lineLayer) this.map.removeLayer(lineLayer);
        if(linePointLayer) this.map.removeLayer(linePointLayer);
        if(drawnItems) this.map.removeLayer(drawnItems);
        this.airlineLayerGroup = [];
        let pointIcon = L.icon({
          iconUrl: require('@/assets/images/marker.png'),
          iconSize: [8, 8]
        });
        var bufferStyle = { //航线缓冲区
          weight: 20,
          color: '#FF7C7A'
        };
        drawnItems = new L.FeatureGroup();
        this.map.addLayer(drawnItems);
        if(lineList.length){
          lineList.map((info, i)=>{
            let linePointArr = [], lineArr = [], polyline = null;
            if(info.linePoints && info.linePoints.length){
              info.linePoints.map((vo, index)=>{
                if(vo.pLat && vo.pLng){
                  lineArr.push([vo.pLat, vo.pLng]);
                  var divHtml = '<span style="padding: 5px;height: 24px;\n' +
                      '    text-align: center;\n' +
                      '    line-height: 24px;\n' +
                      '    border-radius: 4px;border: 2px solid #fff;\n' +
                      '    margin-left: -12px;\n' +
                      '    white-space:nowrap;background:#00E736;color:#fff;font-size:12px;">' +
                      '<span style=" width: 0;\n' +
                      '    height: 0;\n' +
                      '    border: 2px solid #fff;\n' +
                      '    position: absolute;\n' +
                      '    margin-left: -6px;\n' +
                      '    left: 50%;\n' +
                      '    top: 24px;border-top-color: #00E736"></span>'+vo.pName+'</span>';
                  const myDivIcon = L.divIcon({
                    html: divHtml,
                    className: 'my-div-icon',
                    iconAnchor: [5, 30]
                  });
                  let marker = L.marker([vo.pLat, vo.pLng], {icon: myDivIcon});
                  linePointArr.push(marker)
                }
                if(index == info.linePoints.length-1){
                  polyline = L.polyline(lineArr, {color:color}).bindPopup(vo.pName)
                  .bindPopup("<div style='padding:5px;'><b>"+info.lineName+"</b></div>");
                  //线操作
                  polyline.on({
                    //mouseover：移入
                    mouseover: ((e) => {
                      var layer = e.target;
                      layer.setStyle({
                        weight: 5,
                        color: '#00E736',
                      });
                      if (!L.Browser.ie && !L.Browser.opera) {
                        layer.bringToFront();
                        linePointLayer = L.layerGroup(linePointArr);
                        linePointLayer.addTo(this.map);
                      }
                    }),
                    //mouseout：移出
                    mouseout: ((e) => {
                      var layer = e.target;
                      layer.setStyle({
                        weight: 2,
                        opacity: 1,
                        color: 'red'
                      });
                      if(linePointLayer){
                        this.map.removeLayer(linePointLayer);
                      }
                    })
                  });

                  this.airlineLayerGroup.push(polyline);
                  //添加缓冲区
                  this.createBufferedRoute(polyline,bufferStyle);
                  if(i == lineList.length-1){
                    // linePointLayer = L.layerGroup(linePointArr);
                    // linePointLayer.addTo(this.map);
                    lineLayer = L.layerGroup(this.airlineLayerGroup.reverse());
                    lineLayer.addTo(this.map);
                    this.map.fitBounds(this.airlineLayerGroup[0].getBounds());
                  }
                }
              })
            }
          })
        }
      },

      // 创建航线缓冲区
      createBufferedRoute(polyline, bufferStyle) {
        if (fairwayLayer) {
          // 这样子把航道图层删掉才能防止出现连续绘制样式叠加的情况（比如航道越画透明度越深）
          // this.map.removeLayer(fairwayLayer);
        }
        const buffered = turf.buffer(polyline.toGeoJSON(), bufferStyle.weight, {
          units: 'meters'
        });
        // console.log(buffered, 'buffered');
        // console.log(drawnItems, 'drawnItems');
        fairwayLayer = L.geoJSON(buffered, {
          style: function (feature) {
            return {
              color: bufferStyle.color,
              fillOpacity: 0.3,
              dashArray: '5,5',
              interactive: false
            };
          }
        }).addTo(drawnItems);
      },

      // 地图信息是否显示监听
      listenCheck(val){
        if(this.checkItem.includes(val)){
          this.checkItem.forEach((item, index)=>{
            if(item == val){
              this.checkItem.splice(index, 1);
              return false;
            }
          })
        }else{
          this.checkItem.push(val);
        }

        switch (val) {
          case "airspace":
            if(!airspaceLayer) return false;
            if(this.checkItem.includes("airspace")){
              airspaceLayer.addTo(this.map);
            }else{
              this.map.removeLayer(airspaceLayer);
            }
            break;
          case "airport":
            if(!airportLayer) return false;
            if(this.checkItem.includes("airport")){
              airportLayer.addTo(this.map);
            }else{
              this.map.removeLayer(airportLayer);
            }
            break;
          case "airpoint":
            if(!pointLayer) return false;
            if(this.checkItem.includes("airpoint")){
              pointLayer.addTo(this.map);
            }else{
              this.map.removeLayer(pointLayer);
            }
            break;
          case "airline":
            if(!lineLayer) return false;
            if(this.checkItem.includes("airline")){
              lineLayer.addTo(this.map);
              linePointLayer.addTo(this.map);
            }else{
              this.map.removeLayer(lineLayer);
              this.map.removeLayer(linePointLayer);
            }
            break;
        }
      },

      // 清除图层
      clearAllLayer(){
        if(airspaceLayer) this.map.removeLayer(airspaceLayer);
        if(airportLayer) this.map.removeLayer(airportLayer);
        if(pointLayer) this.map.removeLayer(pointLayer);
        if(lineLayer) this.map.removeLayer(lineLayer);
        if(linePointLayer) this.map.removeLayer(linePointLayer);
      },

      // 清空地图信息
      clearMapInfo(){
        this.clearAllLayer();
        airspaceLayer = null;
        airportLayer = null;
        pointLayer = null;
        lineLayer = null;
        linePointLayer = null;
        this.airspaceLayerGroup = [], this.airspaceList = [];
        this.airportList = [], this.airportLayerGroup = [];
        this.airpointList = [], this.airpointLayerGroup = [];
        this.airlineList = [], this.airlineLayerGroup = [];
      },

      /* 
       * 绘制扇形
       * @params center 扇形中心点 Array [31.59586, 120.2995]
       * @params radius 扇形半径 Number
       * @params startArc 起始角度 Number -180-180 逆时针取值
       * @params stopArc 终止角度 Number -180-180 逆时针取值
       * @params pointNum 圆弧上点的个数 Number
      */
      getPoints(center, radius, startArc, stopArc, pointNum){
        var sin;
        var cos;
        var x;
        var y;
        var angle;
        var points = [];
        points.push(center);
        for (var i = 0; i <= pointNum; i++) {
            angle = startArc + (stopArc - startArc) * i / pointNum;
            sin = Math.sin(angle * Math.PI / 180);
            cos = Math.cos(angle * Math.PI / 180);
            y = center[0] + radius * cos;
            x = center[1] + radius * sin;
            points[i] = [y, x];
        }
        var point = points;
        point.push(center);
        return point;
      },
      drawSector(center, radius, startArc, stopArc, pointNum){
        var points = this.getPoints(center, radius, startArc, stopArc, pointNum);
        points[points.length] = points[0];
        sector = L.polygon(points, {color:"purple"}).addTo(this.map).bindPopup("(*^▽^*)").openPopup();
      },

      // 度转度分秒
      D2Dms (d_data = 0) {
        let degree = parseInt(d_data);
        let min = parseInt((d_data - degree) * 60);
        let sec = Math.round((d_data - degree) * 3600 - min * 60);
        return degree + "°" + min + "′" + sec + "″";
      },
    },
    beforeDestroy(){
      if(this.map){
        this.map.off();
        this.map.remove();
        let container = L.DomUtil.get("map");
        if(container) container._leaflet_id = null;
        this.map = null;
        this.$parent.$refs.mapShow.map = null;
      }
    },
  }
</script>
<style scoped>
  #mainPart{
    width:100%;
    height:100vh;
    padding:0;
    overflow: hidden;
    position:relative;
  }
  /* div >>> .leaflet-top.leaflet-left{
    left:10px;
    top:90px!important;
  } */
  /* 地图 */
  #map{
    width:100%;
    height:100%;
    padding:0;
    margin:0;
    position: relative;
  }
  .airportIcon{
    width:5px;
    height:5px;
    display:block;
    background-color:red;
    border-radius:100%;
  }
  /* 点位显示 */
  #currentPoint{
    height:30px;
    line-height:20px;
    font-size:14px;
    background-color:#F2F2F2;
    padding:5px 8px;
    margin:0;
    position:absolute;
    bottom:10px;
    right:10px;
    z-index:999;
  }
  /* 图例 */
  dl.tipItem{
    width:90px;
    height:100px;
    background-color:#F2F2F2;
    border-radius:5px;
    position:absolute;
    bottom:10px;
    right:10px;
    z-index:999;
  }
  dl.tipItem dt{
    width:100%;
    height:28px;
    line-height:28px;
    font-size:14px;
    text-align:center;
    color:#FFF;
    background-color:#1f2d3d;
    border-bottom:1px solid #1f2d3d;
    border-radius:5px 5px 0 0;
  }
  dl.tipItem dd{
    width:100%;
    height:36px;
    line-height:36px;
    text-align: left;
    display:inline-block;
    padding:0 10px;
    margin:0;
  }
  dl.tipItem dd img{
    width:20px;
    vertical-align:middle;
    margin-right:14px;
  }

  /* 表格 */
  .el-table{
    width:calc(100% - 16px);
    font-size:13px;
    border:1px solid #243F63;
  }
  .el-table td, .el-table th, .el-table--small td, .el-table--small th{
    padding:4px 0!important;
    height:30px;
    padding:5px 0;
  }
  .el-table th, .el-table thead.is-group th, .el-table--small th{
    height: 30px!important;
    background-color:#063761!important;
    font-size:13px;
    color:#FFF;
    border:1px solid #063761;
  }
  .el-table thead.is-group th{
    border-bottom:1px solid #063761;
  }
  .el-table .cell{
    height:100%;
    line-height:29px;
    text-align:center;
    overflow: hidden;
    white-space: nowrap!important;
    text-overflow: ellipsis;
  }
  .el-table__body tr.current-row>td,
  .el-table--enable-row-hover .el-table__body tr:hover>td,
  .el-table__body tr.hover-row>td.el-table__cell,
  .el-table__body tr.el-table__row:hover td.el-table__cell{
    background-color: #156FA1!important;
    color: #FFF;
    cursor: pointer;
  }
  .el-table td .el-button{margin:0px!important;}
  .el-table td .el-button--text span{
    letter-spacing: 1px;
    border-bottom: 1px solid;
    padding-bottom:1px;
    margin: 0 3px;
  }
  .el-table--border:after, .el-table--group:after, .el-table:before{
    background-color:transparent!important;
  }
  .el-table, .el-table >>> th{
    color:#FFF;
    background-color:transparent;
    border:none!important;
    margin:0;
  }
  .el-table >>> th{
    border:none!important;
    background-color:#071629!important;
  }
  .el-table >>> th.el-table__cell, .el-table >>> td.el-table__cell{
    border:none!important;
  }
  .el-table >>> tbody tr:hover td{
    background-color:#0A1B31;
  }
  .el-table >>> tbody tr:nth-child(odd){
    background-color:#0A1B31;
  }
  .el-table >>> tbody tr:nth-child(even){
    background-color:#071629;
  }
  .el-table >>> .el-table__header-wrapper th,
  .el-table >>> .el-table__fixed-header-wrapper th{
    background-color:#000A2E;
    border:none!important;
    color:#e6dede;
  }
  .el-table >>> td.el-table__cell, .el-table >>> th.el-table__cell.is-leaf{
    border:none!important;
    background-color:transparent;
    line-height:29px;
  }
</style>